package com.caishichang.infosysdesign.controller.user;

import com.caishichang.infosysdesign.entity.User;
import com.caishichang.infosysdesign.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {


    @Autowired
    UserService userService;

    /**
     * 登录
     *
     * @return
     */
    @GetMapping({"", "/login"})
    public String login() {
        return "user/login";
    }

    /**
     * @param userName
     * @param password
     * @param session
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestParam("userName") String userName,
                        @RequestParam("password") String password,
                        HttpSession session) {
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            session.setAttribute("errorMsg", "用户名或密码不能为空");
            return "user/login";
        }

        User user = userService.login(userName, password);
        if (user != null) {
            // session.setAttribute("loginUser", user.getUserName());
            // session.setAttribute("loginUserId", user.getUserId());
            session.setAttribute("user", user);
            //session过期时间设置为7200秒 即两小时
            //session.setMaxInactiveInterval(60 * 60 * 2);
            return "redirect:/user/strategy";
        } else {
            session.setAttribute("errorMsg", "登陆失败");
            return "user/login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/";
    }
}
